<?php

/**
 * Compose the "Current Release Info" form.
 */
function jnj_deploy_tool_release_info_form($form_state) {
  $form['info'] = array(
    '#type' => 'textarea',
    '#title' => t('Release Info'),
    '#description' => t("Current release info."),
    '#default_value' => variable_get('jnj_deploy_tool_release_info', ''),
  );

  return $form;
}

/**
 * Compose the "Generate Package" form.
 */
function jnj_deploy_tool_generate_form($form_state) {
  
  drupal_add_js(drupal_get_path('module', 'jnj_deploy_tool') . '/js/jnj_deploy_tool.js');
  
  $form['generate'] = array(
    '#type' => 'fieldset',
    '#title' => t('Generate Deployment Package (Multisite Version)'),
  );

  list($drupal_modules_path, $drupal_themes_path, $drupal_files_path, $drupal_sqldump_path) = _jnj_deploy_tool_settings_variables(true);

  $form['generate']['settings'] = array(
    '#value' => '<p><strong>Settings</strong></p>' .
      'MODULES: ' . ($drupal_modules_path ? '<span style="color: green;">' . $drupal_modules_path . '</span>' : '<span style="color: red;">NO</span>') . '<br />' .
      'THEMES: ' . ($drupal_themes_path ? '<span style="color: green;">' . $drupal_themes_path . '</span>' : '<span style="color: red;">NO</span>') . '<br />' .
      'FILES: ' . ($drupal_files_path ? '<span style="color: green;">' . $drupal_files_path . '</span>' : '<span style="color: red;">NO</span>') . '<br />' .
      'TARGET: <span style="color: green;">' . jnj_deploy_tool_get_output_path() . '</span><br />' .
      '<br />',
  );
  
  // build files section
  $form['generate']['database'] = array(
    '#type' => 'fieldset',
    '#title' => t('Database settings'),
    '#collapsible' => TRUE,
    '#collapsed' => TRUE,
  );
  
  $form['generate']['database']['include_db'] = array(
    '#type' => 'checkbox',
    '#default_value' => 'true',
    '#title' => t('Include database in the deployment package.'),
  );
  
  $modules = jnj_deploy_tool_get_allowed_modules($drupal_modules_path);
  
  $form['generate']['modules'] = jnj_deploy_tool_get_settings_section('modules', 'Modules', $modules);
  
  // build themes section
  $themes = jnj_deploy_tool_get_dirs($drupal_themes_path);
  $form['generate']['themes'] = jnj_deploy_tool_get_settings_section('themes', 'Themes', $themes);
  
  // build files section
  $form['generate']['files'] = array(
    '#type' => 'fieldset',
    '#title' => t('Files'),
    '#collapsible' => TRUE,
    '#collapsed' => TRUE,
    '#description' => t('Files that will be included in the deployment package.'),
  );
  
  $form['generate']['files']['files_radio'] = array(
    '#type' => 'radios',
    '#title' => t('Files'),
    '#default_value' => 'all',
    '#options' => array('all' => t('All Files'), 'list' => t('Enter files')),
  );

  $form['generate']['files']['files_list'] = array(
    '#type' => 'textarea',
    '#title' => t('Files list'),
    '#attributes' => array('class' => 'files_textarea'),
    '#description' => t("Enter one file per line as the exact name of the file in the sites/default/files directory. Ex: image_example_001.jpg"),
    '#rows' => 5
  );
  
  // build files section
  $form['generate']['release_info'] = array(
    '#type' => 'fieldset',
    '#title' => t('Release Info'),
    '#collapsible' => TRUE,
    '#collapsed' => TRUE,
  );
  
  $form['generate']['release_info']['info'] = array(
    '#type' => 'textarea',
    '#description' => t("Release info for this package."),
    '#default_value' => date("Y-m-d\TH-i-s"),
    '#rows' => 5
  );
  
  $form['generate']['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Generate Deployment Package')
  );

  $form['generate']['os'] = array(
    '#value' => '<p>' . t('Server Operating System: ') . (jnj_deploy_tool_server_is_windows() ? t('Windows') : t('Non Windows')) . '</p>',
  );

  return $form;
}

/**
 * Gets a section of settings.
 */
function jnj_deploy_tool_get_settings_section($type, $title, $options) {

  $array = array(
    '#type' => 'fieldset',
    '#title' => t($title),
    '#collapsible' => TRUE,
    '#collapsed' => TRUE,
    '#description' => t($title. ' that will be included in the deployment package.'),
  );
  
  $array[$type .'_radio'] = array(
    '#type' => 'radios',
    '#title' => t($title),
    '#default_value' => 'all',
    '#options' => array('all' => t('All '. $title), 'list' => t('Choose From a List')),
  );
  
  $array[$type .'_list'] = array(
    '#type' => 'checkboxes',
    '#options' => $options,
    '#attributes' => array('class' => $type. '_checkboxes')
  );
  
  return $array;
}

/**
 * Submit hook for the jnj_deploy_tool_generate_form.
 */
function jnj_deploy_tool_generate_form_submit($form, &$form_state) {
  list($drupal_modules_path, $drupal_themes_path, $drupal_files_path, $drupal_sqldump_path) = _jnj_deploy_tool_settings_variables();

  $drupal_temp_dir = file_directory_temp();
  $output_dir = $drupal_temp_dir .'/'. jnj_deploy_tool_get_output_folder_name();
  $site_dir = $output_dir .'/'. jnj_deploy_tool_get_site_folder(); 
  $work_dir = $drupal_temp_dir .'/'. uniqid('jnj_deploy_tool');

  jnj_deploy_tool_set_time_limit();

  // Progress messages and error control variables.
  $ok = TRUE;

  // Create temporary work directory.
  $options = array(
    'action' => 'function_mkdir',
    'message' => t('Creating temporary work directory... '),
    'targets' => array(
      $work_dir,
    ),
  );
  
  $ok &= _jnj_deploy_tool_action($options);
  
  // get modules list
  $modules_radio = $form_state['values']['modules_radio'];
  $modules = array();
  if ($modules_radio == 'list') {
    $modules_list = $form_state['values']['modules_list'];

    foreach ($modules_list as $module => $checked) {
      if ($checked != FALSE) {
        $modules[] = $module;
      }
    }
  } else {
    $modules = jnj_deploy_tool_get_allowed_modules($drupal_modules_path);
  }
  
  // get themes list
  $themes_radio = $form_state['values']['themes_radio'];
  $themes = array();
  if ($themes_radio == 'list') {
    $themes_list = $form_state['values']['themes_list'];

    foreach ($themes_list as $theme => $checked) {
      if ($checked != FALSE) {
        $themes[] = $theme;
      }
    }
  } else {
    $themes = jnj_deploy_tool_get_dirs($drupal_themes_path);
  }
  
  
  jnj_deploy_tool_copy_dirs($modules, $work_dir .'/modules', $drupal_modules_path, 'modules');
  jnj_deploy_tool_copy_dirs($themes, $work_dir .'/themes', $drupal_themes_path, 'themes');


  if ($drupal_files_path) {
    // get files list
    $files_radio = $form_state['values']['files_radio'];
    $files_dir = $work_dir .'/files';
    
    // create the directory and copy the files
    jnj_deploy_tool_create_dir($work_dir .'/files');
    if ($files_radio == 'list') {
      $files_string = $form_state['values']['files_list'];
      $files = explode("\n", $files_string);
      
      foreach ($files as $file) {
        $file = trim($file);       
        if ($file != '') {
          // Creating internal file folders
          $path_folders = explode('/',$file);
          if(count($path_folders) > 1) {
            array_pop($path_folders); // remove filename
            $path = $files_dir;
            foreach($path_folders as $index => $folder) {
              $path .= '/'. $folder;
              if(file_exists($path) === FALSE)
                jnj_deploy_tool_create_dir($path);
            }
          }
          $file_path = $drupal_files_path .'/'. $file;
          $options = array(
            'action' => 'command_cp',
            'message' => t('Copying file: ') . $file .'...',
            'targets' => array(
              escapeshellarg($file_path),
              escapeshellarg($files_dir .'/'. $file)
            ),
          );
          
          $ok &= _jnj_deploy_tool_action($options);
        }
      }
    } else {
      // copy the whole directory
      jnj_deploy_tool_tar($drupal_files_path, $files_dir, 'files');
    }
  }

  // Make sure that the output directory exists.
  $options = array(
    'action' => 'function_mkdir',
    'message' => t('Making sure that the output directory exists... '),
    'targets' => array(
      $output_dir,
    ),
  );
  
  $ok &= _jnj_deploy_tool_action($options);
  // Make sure that the output site directory exists.
  $options = array(
    'action' => 'function_mkdir',
    'message' => t('Making sure that the output site directory exists... '),
    'targets' => array(
      $site_dir,
    ),
  );
  
  $ok &= _jnj_deploy_tool_action($options);

  // Remove old sqldump.sql.gz. This prevents a WARNING message under Windows.
  $command = 'rm -rf '. $drupal_sqldump_path;
  system($command);
  
  $include_db = $form_state['values']['include_db'];
  
  if ($include_db) {
    $ok &= jnj_deploy_tool_backup_database($drupal_sqldump_path, $work_dir .'/sqldump.sql.gz');
  }

  // Create the release info text file.
  @file_put_contents($work_dir . '/rel_info.txt', $form['generate']['release_info']['info']['#value']);

  // Remove unwanted modules.
  jnj_deploy_tool_remove_unwanted_modules($work_dir);
  
  //remove the .svn dirs, for local depoyment generate...
  $command = ' rm -rf'. $work_dir .'`find . -type d -name .svn`';
  system($command);
  
  // Remove previously generated packages from the output directory.
  $command = 'rm -rf '. $site_dir .'/'. variable_get('jnj_deploy_tool_packagename', 'backup.tgz') .'*';
  system($command);

  // Compress package in the output directory.
  $options = array(
    'action' => 'command_tar_split',
    'message' => t('Compressing packages in the work directory... '),
    'targets' => array(
      $work_dir,
      variable_get('jnj_deploy_tool_partmaxsize', '4096'),
      $site_dir,
      variable_get('jnj_deploy_tool_packagename', 'backup.tgz'),
    ),
  );
  $ok &= _jnj_deploy_tool_action($options);

  // Merge package in the output directory.
  $command = 'rm -rf ' . $site_dir . '/merged_' . variable_get('jnj_deploy_tool_packagename', 'backup.tgz');
  system($command);
  $options = array(
    'action' => 'command_cat',
    'message' => t('Creating merged package (download friendly)...'),
    'targets' => array(
      $site_dir,
      variable_get('jnj_deploy_tool_packagename', 'backup.tgz'),
      $site_dir,
      variable_get('jnj_deploy_tool_packagename', 'backup.tgz'),
    ),
  );
  $ok &= _jnj_deploy_tool_action($options);

  // Remove work directory.
  $command = 'rm -rf ' . $work_dir;
  system($command);

  if ($ok) {
    drupal_set_message(t('Process completed successfully!'));
  } else {
    drupal_set_message(t('Something wrong happened during the process. Please check the messages above!'), 'error');
  }
}

/**
 * Copy an array of directories from drupal folder to a temporary folder.
 */
function jnj_deploy_tool_copy_dirs($list, $temp_path, $drupal_path, $type) {
  if ($drupal_path) { 
    // Copy temp directory to the work dir.
    jnj_deploy_tool_create_dir($temp_path);
    
    foreach ($list as $item) {
      $from = $drupal_path .'/'. $item;
      $to = $temp_path .'/'. $item;

      jnj_deploy_tool_create_dir($to);
      jnj_deploy_tool_tar($from, $to, $type);
    }
  }
}

/**
 * Compose the "Settings" form.
 */
function jnj_deploy_tool_settings_form($form_state) {

  $drupal_temp_path = file_directory_temp();
  //$drupal_files_path = file_directory_path();
  //$drupal_modules_path = jnj_deploy_tool_get_modules_path();
  //$drupal_themes_path = jnj_deploy_tool_get_themes_path();

  list($drupal_modules_path, $drupal_themes_path, $drupal_files_path, $drupal_sqldump_path) = _jnj_deploy_tool_settings_variables(TRUE);
  
  $form['generate'] = array(
    '#type' => 'fieldset',
    '#title' => t('Deployment Package generation settings'),
  );
  
  $form['generate']['settings'] = array(
    '#value' => '<strong>Paths:</strong><br />'.
      'TEMP: '. ($drupal_temp_path ? '<span style="color: green;">'. $drupal_temp_path .'</span>' : '<span style="color: red;">NO</span>') .'<br />' .
      'FILES: '. ($drupal_files_path ? '<span style="color: green;">'. $drupal_files_path .'</span>' : '<span style="color: red;">NO</span>') .'<br />'.
      'MODULES: '. ($drupal_modules_path ? '<span style="color: green;">'. $drupal_modules_path .'</span>' : '<span style="color: red;">NO</span>') .'<br />'.
      'THEMES: '. ($drupal_themes_path ? '<span style="color: green;">'. $drupal_themes_path .'</span>' : '<span style="color: red;">NO</span>') .'<br />',
  );

  $form['generate']['jnj_deploy_tool_outputdir'] = array(
    '#type' => 'textfield',
    '#title' => t('Output directory name'),
    '#description' => t("Directory name where the generated deployment packages will be placed. This directory will be created under the drupal's temporary directory."),
    '#maxlength' => 255,
    '#required' => TRUE,
    '#default_value' => jnj_deploy_tool_get_output_folder_name(),
  );

  $form['generate']['jnj_deploy_tool_packagename'] = array(
    '#type' => 'textfield',
    '#title' => t('Deployment package main name'),
    '#description' => t('Package\'s main file name. Letters will be appended for additional parts when necessary. E.g.: backup.tgz'),
    '#maxlength' => 255,
    '#required' => TRUE,
    '#default_value' => variable_get('jnj_deploy_tool_packagename', 'backup.tgz'),
  );

  $form['generate']['jnj_deploy_tool_partmaxsize'] = array(
    '#type' => 'textfield',
    '#title' => t('Max size for deployment package parts'),
    '#description' => t('Specify an integer value, in kilobytes. E.g.: 4096'),
    '#maxlength' => 255,
    '#required' => TRUE,
    '#default_value' => variable_get('jnj_deploy_tool_partmaxsize', '4096'),
  );
  
  $form['generate']['jnj_deploy_tool_max_exec_time'] = array(
    '#type' => 'textfield',
    '#title' => t('Max execution time for the deployment session'),
    '#description' => t('Specify an integer value, in seconds. E.g.: 300'),
    '#maxlength' => 5,
    '#required' => TRUE,
    '#default_value' => variable_get('jnj_deploy_tool_max_exec_time', '300'),
  );

  return system_settings_form($form);
}

/**
 * Validations for the Settings form
 */
function jnj_deploy_tool_settings_form_validate($form, &$form_state) {
  if (!jnj_deploy_tool_validate_dir_name($form['generate']['jnj_deploy_tool_outputdir']['#value'])) {
    form_set_error('jnj_deploy_tool_tempdir', t('The specified output directory name is invalid.'));
  }
}

/**
 * Implementation of the upload form.
 */
function jnj_deploy_tool_upload_form($form_state) {
  
  drupal_add_js(drupal_get_path('module', 'jnj_deploy_tool') . '/js/swfupload.js');
  drupal_add_js(drupal_get_path('module', 'jnj_deploy_tool') . '/js/fileprogress.js');
  drupal_add_js(drupal_get_path('module', 'jnj_deploy_tool') . '/js/handlers.js');
  drupal_add_js(drupal_get_path('module', 'jnj_deploy_tool') . '/js/swfupload.queue.js');
  drupal_add_css(drupal_get_path('module', 'jnj_deploy_tool') . '/css/default.css');
  
  // make sure the directories exist
  $output_dir = file_directory_temp() .'/'. jnj_deploy_tool_get_output_folder_name();
  jnj_deploy_tool_create_dir($output_dir);
  jnj_deploy_tool_create_dir($output_dir .'/'. jnj_deploy_tool_get_site_folder());
  
  $script = '
<script type="text/javascript">
  var swfu;

  $(document).ready(function(){
    var settings = {
      flash_url : "'. base_path() . drupal_get_path('module', 'jnj_deploy_tool') .'/js/swfupload.swf",
      upload_url: "'. base_path() . drupal_get_path('module', 'jnj_deploy_tool') .'/jnj_deploy_tool_upload.php",
      post_params: {
        "PHPSESSID" : "'. session_id() .'",
        "UPLOAD_DIRECTORY" : "'. jnj_deploy_tool_get_output_path() .'",
        "PACKAGE_NAME" : "'. variable_get('jnj_deploy_tool_packagename', 'backup.tgz') .'"
      },
      file_size_limit : "12 MB",
      file_types : "*.*",
      file_types_description : "All Files",
      file_upload_limit : 100,
      file_queue_limit : 0,
      custom_settings : {
      progressTarget : "fsUploadProgress",
      cancelButtonId : "btnCancel"
    },
    debug: false,

    // Button settings.
    button_image_url: "/'. drupal_get_path('module', 'jnj_deploy_tool') .'/images/TestImageNoText_65x29.png",
    button_width: "65",
    button_height: "29",
    button_placeholder_id: "spanButtonPlaceHolder",
    button_text: \'<span class="theFont">UPLOAD</span>\',
    button_text_style: ".theFont { font-size: 13px; font-family: Arial; font-weight: bold; }",
    button_text_left_padding: 3,
    button_text_top_padding: 5,

    // The event handler functions are defined in handlers.js
    file_queued_handler : fileQueued,
    file_queue_error_handler : fileQueueError,
    file_dialog_complete_handler : fileDialogComplete,
    upload_start_handler : uploadStart,
    upload_progress_handler : uploadProgress,
    upload_error_handler : uploadError,
    upload_success_handler : uploadSuccess,
    upload_complete_handler : uploadComplete,
    queue_complete_handler : queueComplete // Queue plugin event.
  };

  swfu = new SWFUpload(settings);
});
</script>
<div class="fieldset flash" id="fsUploadProgress">
  <span class="legend">Upload Queue</span>
</div>
<div id="divStatus">0 Files Uploaded</div>
<div>
  <span id="spanButtonPlaceHolder"></span>
  <input id="btnCancel" type="button" value="Cancel All Uploads" onclick="swfu.cancelQueue();" disabled="disabled" style="margin-left: 2px; font-size: 8pt; height: 29px;" />
</div>
  ';

  $form['generate']['settings2'] = array(
    '#value' => $script,
  );

  $form['jnj_deploy_tool_file_to_upload'] = array(
    '#type' => 'file',
    '#title' => t('File to Upload'),
  );

  $form['jnj_deploy_tool_upload_button'] = array(
    '#type' => 'submit',
    '#value' => t('Upload'),
    '#submit' => array('jnj_deploy_tool_upload_file'),
  );

  list($drupal_modules_path, $drupal_themes_path, $drupal_files_path, $drupal_sqldump_path) = _jnj_deploy_tool_settings_variables(true);
  
  $form['generate']['settings'] = array(
    '#value' => '<p><strong>Settings</strong></p>' .
      'MODULES: ' . ($drupal_modules_path ? '<span style="color: green;">' . $drupal_modules_path . '</span>' : '<span style="color: red;">NO</span>') . '<br />' .
      'THEMES: ' . ($drupal_themes_path ? '<span style="color: green;">' . $drupal_themes_path . '</span>' : '<span style="color: red;">NO</span>') . '<br />' .
      'FILES: ' . ($drupal_files_path ? '<span style="color: green;">' . $drupal_files_path . '</span>' : '<span style="color: red;">NO</span>') . '<br />' .
      'BACKUP DB: ' . ((variable_get('jnj_deploy_tool_sqldump_radio', 'true') == 'true') ? '<span style="color: green;">YES</span>' : '<span style="color: red;">NO</span>') . '<br />' .
      '<br />',
  );

  $files_uploaded = jnj_deploy_tool_get_uploaded_files();
  if ($files_uploaded) {
    $form['jnj_deploy_tool_files_uploaded'] = array(
      '#type' => 'select',
      '#title' => t('Already Uploaded Files'),
      '#multiple' => TRUE,
      '#options' => $files_uploaded,
      '#size' => 10,
    );


    $form['jnj_deploy_tool_clean_button'] = array(
      '#type' => 'submit',
      '#submit' => array('jnj_deploy_tool_clean_files_uploaded'),
      '#value' => t('Clean'),
    );

  } else {
    $form['no_uploaded_file'] = array(
    '#value' => t('<p>No file was uploaded yet.</p>'),
    );
  }

  $form['#attributes'] = array('enctype' => 'multipart/form-data');

  return $form;
}

/**
 * Implementation of the custom files form.
 */
function jnj_deploy_tool_custom_files_form($form_state) {
  
  $apache_custom_file = jnj_deploy_tool_get_apache_custom_path();
  $php_custom_file = jnj_deploy_tool_get_php_custom_path();
  
  if (file_exists($apache_custom_file)) {
    $apache_custom = file_get_contents($apache_custom_file);
  }
  
  if (file_exists($php_custom_file)) {
    $php_custom = file_get_contents($php_custom_file);
  }
  
  // apache custom
  $form['custom_files']['apache_custom'] = array(
    '#type' => 'fieldset',
    '#title' => t('Apache Custom'),
    '#collapsible' => TRUE,
    '#collapsed' => TRUE,
    '#description' => t('Apache custom file content'),
  );
  
  $form['custom_files']['apache_custom']['apache_custom_content'] = array(
    '#type' => 'textarea',
    '#rows' => 15,
    '#default_value' => $apache_custom,
  );
  
  // custom php settings
  $form['custom_files']['php_custom'] = array(
    '#type' => 'fieldset',
    '#title' => t('Custom PHP Settings'),
    '#collapsible' => TRUE,
    '#collapsed' => TRUE,
    '#description' => t('Custom PHP Settings content'),
  );
  
  $form['custom_files']['php_custom']['php_custom_content'] = array(
    '#type' => 'textarea',
    '#rows' => 15,
    '#default_value' => $php_custom,
  );
  
  $form['custom_files']['jnj_deploy_tool_save_button'] = array(
    '#type' => 'submit',
    '#value' => t('Save'),
  );
    
  return $form;
}

/**
 * Implementation of the custom files form submit.
 */
function jnj_deploy_tool_custom_files_form_submit($form, &$form_state) {
  $apache_custom = $form_state['values']['apache_custom_content'];
  $php_custom = $form_state['values']['php_custom_content'];
  $email = variable_get('site_mail', '');
  
  $apache_custom_file = jnj_deploy_tool_get_apache_custom_path();
  $php_custom_file = jnj_deploy_tool_get_php_custom_path();
  $flag_file = jnj_deploy_tool_get_flag_file_path();
  
  file_put_contents($apache_custom_file, $apache_custom);
  file_put_contents($php_custom_file, $php_custom);
  file_put_contents($flag_file, $email);
  
  drupal_set_message("Custom files saved. A message will be sent to the administrator's e-mail when the apache restarts.");
}

/**
 * Implementation of the deploy form.
 */
function jnj_deploy_tool_deploy_form($form_state) {
  $drupal_temp_dir = file_directory_temp();
  $backup_package_name = variable_get('jnj_deploy_tool_packagename', 'backup.tgz');
  $work_dir = $drupal_temp_dir . '/'. uniqid('jnj_deploy_tool');
  $deploy_dir = jnj_deploy_tool_get_output_path();
  
  // Merge deployment package parts into a single TGZ file.
  $command = 'cat '. $deploy_dir .'/'. $backup_package_name .'* | tar -tz';
  exec($command, $output, $retval);
  if ($output === FALSE || $retval != 0) {
    drupal_set_message(t('Insufficient or invalid deployment package parts into the work directory...'), 'error');
    return FALSE;
  }
  
  $files_count = $modules_count = $themes_count = 0;
  $modules = $themes = $files = '';
  $db_found = '<span style="color: red;"> database dump NOT FOUND.</span>';
  
  foreach ($output as $line) {
    $pattern_module = '%^./modules/([^/]+)/$%i';
    $pattern_themes = '%^./themes/([^/]+)/$%i';
    $pattern_files = '%^./files/.*[^/]$%i';
    
    if (preg_match($pattern_module, $line, $matches)) {
      $modules .= '[<span style="color: green;">' . $matches[1] .'</span>] ';
      $modules_count++;
    }
    
    if (preg_match($pattern_themes, $line, $matches)) {
      $themes .= '[<span style="color: green;">' . $matches[1] .'</span>] ';
      $themes_count++;
    }
    
    if (preg_match($pattern_files, $line, $matches)) {
      $files_count++;
    }
    
    if ($line == './sqldump.sql.gz') {
      $db_found = '<span style="color: green;"> database dump found.</span>';
    }
  }
  
  $form['deploy']['contents'] = array(
    '#type' => 'fieldset',
    '#title' => t('Deployment Package Contents'),
  );
  
  $form['deploy']['contents']['deploy_contents'] = array(
    '#value' => '<b>Modules ('. $modules_count .'):</b> <span style="color: blue;">' . $modules . '</span><br />'.
      '<b>Themes ('. $themes_count .'):</b> <span style="color: blue;">' . $themes . '</span><br />'.
      '<b>Files folder:</b> <span style="color: green;">'. $files_count .' files found.</span><br />'.
      '<b>Database:</b> '. $db_found .'<br />'.
      '<b>TARGET:</b> <span style="color: green;">' . jnj_deploy_tool_get_output_path() . '</span><br />'
  );
  
  $form['deploy']['settings'] = array(
    '#type' => 'fieldset',
    '#title' => t('Deployment Settings'),
  );
  
  $form['deploy']['settings']['clear_modules'] = array(
    '#type' => 'checkbox',
    '#default_value' => 'true',
    '#title' => t('Remove current contents from <b>modules</b> folder before deploying new package.'),
  );
  
  $form['deploy']['settings']['clear_themes'] = array(
    '#type' => 'checkbox',
    '#default_value' => 'true',
    '#title' => t('Remove current contents from <b>themes</b> folder before deploying new package.'),
  );
  
  $form['deploy']['settings']['clear_files'] = array(
    '#type' => 'checkbox',
    '#default_value' => 'true',
    '#title' => t('Remove current contents from <b>files</b> folder before deploying new package.'),
  );
 
  $url = base_path(). 'admin/settings/deploy/downloads';
  
  $form['deploy']['warning'] = array(
    '#value' => '<b style="color: red;">Warning: The backup files will be available for download in the <a href="'. $url .'">Downloads</a> tab when "Backup" button is clicked. Once the deployment is trigged, the backup files and deployment package will be deleted.</b><br/>'
  );
  
  $form['backup_button'] = array(
    '#type' => 'submit',
    '#submit' => array('jnj_deploy_tool_backup_site'),
    '#value' => t('Backup'),
  );
  
  $form['submit_button'] = array(
    '#type' => 'submit',
    '#value' => t('Deploy'),
  );

  return $form;
}

/**
 * Deploys the website.
 */
function jnj_deploy_tool_deploy_form_submit($form, &$form_state) {
  list($drupal_modules_path, $drupal_themes_path, $drupal_files_path, $drupal_sqldump_path) = _jnj_deploy_tool_settings_variables();
  
  jnj_deploy_tool_set_time_limit();
  
  $clear_modules = $form_state['values']['clear_modules'];
  $clear_themes = $form_state['values']['clear_themes'];
  $clear_files = $form_state['values']['clear_files'];
  $ok = TRUE;
  
  $work_dir = jnj_deploy_tool_extract_package();
  if ($work_dir === FALSE) {
    return;
  }
  
  jnj_deploy_tool_clear_directories($clear_modules, $clear_themes, $clear_files);
  
  // Overwrite Modules.
  if ($drupal_modules_path) {
    $options = array(
      'action' => 'command_cp_r',
      'message' => t('Overwriting modules... '),
      'targets' => array(
        $work_dir . '/modules/*',
        $drupal_modules_path,
      ),
    );
    $ok &= _jnj_deploy_tool_action($options);
  }

  // Overwrite Themes.
  if ($drupal_themes_path) {
    $options = array(
      'action' => 'command_cp_r',
      'message' => t('Overwriting themes... '),
      'targets' => array(
        $work_dir . '/themes/*',
        $drupal_themes_path,
      ),
    );
    $ok &= _jnj_deploy_tool_action($options);
  }

  // Overwrite Files.
  if ($drupal_files_path) {
    $options = array(
      'action' => 'command_cp_r',
      'message' => t('Overwriting files... '),
      'targets' => array(
        $work_dir . '/files/*',
        $drupal_files_path,
      ),
    );
    $ok &= _jnj_deploy_tool_action($options);
  }
  
  // Backup settings variables.
  $settings = array();
  jnj_deploy_tool_backup_variables($settings);

  // Restore New Dump.
  if (file_exists($work_dir . '/sqldump.sql.gz')) {
    _backup_migrate_restore_file($work_dir . '/sqldump.sql.gz', "", TRUE);
  }

  // Restore settings variables.
  jnj_deploy_tool_restore_variables($settings);

  // Read the release info text file.
  variable_set('jnj_deploy_tool_release_info', file_get_contents($work_dir .'/rel_info.txt'));

  // delete work and output dir contents. 
  jnj_deploy_tool_delete_dir_contents($work_dir);

  if (!$ok) {
    drupal_set_message(t('Something wrong happened during the process. Please check the messages above!'), 'error');
  } else {
    jnj_deploy_tool_delete_dir_contents(jnj_deploy_tool_get_output_path());
    drupal_goto('admin/settings/deploy');
  }
}

/**
 * Delete files from the site/default/files folder.
 */
function jnj_deploy_tool_delete_files_form($form_state) {

  $form['delete_files']['delete_files_content'] = array(
    '#title' => '',
    '#type' => 'textarea',
    '#rows' => 15,
    '#title' => t('Files list'),
    '#description' => t("Enter one file per line as the exact name of the file in the sites/default/files directory. Ex: image_example_001.jpg"),
  );
  
  $form['delete_files']['jnj_deploy_tool_delete_button'] = array(
    '#type' => 'submit',
    '#value' => t('Delete'),
  );
    
  return $form; 
}

/**
 * Delete files from the site/default/files folder.
 */
function jnj_deploy_tool_delete_files_form_submit($form, &$form_state) {
  $files_string = $form_state['values']['delete_files_content'];
  $dir_path = realpath(file_directory_path());
  $files = explode("\n", $files_string);
  
  jnj_deploy_tool_set_time_limit();
  
  foreach ($files as $file) {
    $file = trim($file);
    $file_path = realpath($dir_path .'/'. $file);
    
    if ($file_path !== FALSE && strpos($file_path, $dir_path) !== FALSE && $dir_path != $file_path) {
      if (is_dir($file_path)) {
        jnj_deploy_tool_delete_dir_contents($file_path);
        rmdir($file_path);
      } else {
        file_delete($file_path);        
      }
    } else {
      drupal_set_message(t('Error trying to delete file: '). $file .'.', 'error');
    }
  }
}

/**
 * Backup everything before deploying a new package.
 */
function jnj_deploy_tool_backup_site($form, &$form_state) {
  list($drupal_modules_path, $drupal_themes_path, $drupal_files_path, $drupal_sqldump_path) = _jnj_deploy_tool_settings_variables(true);
  $drupal_temp_dir = file_directory_temp();
  $output_dir = $drupal_temp_dir .'/'. jnj_deploy_tool_get_output_folder_name();
  $site_dir = $output_dir .'/'. jnj_deploy_tool_get_site_folder();
  
  jnj_deploy_tool_set_time_limit();
  
  // Backup database
  jnj_deploy_tool_backup_database($drupal_sqldump_path, $site_dir .'/autobackup_database.sql.gz');
  jnj_deploy_tool_tar_zip($drupal_modules_path, $site_dir .'/autobackup_modules.tar.gz');
  jnj_deploy_tool_tar_zip($drupal_themes_path, $site_dir .'/autobackup_themes.tar.gz');
  jnj_deploy_tool_tar_zip($drupal_files_path, $site_dir .'/autobackup_files.tar.gz');
}

/**
 * Validations for the Packages Upload / Deploy form
 */
function jnj_deploy_tool_upload_form_validate($form, &$form_state) {
  if ($form_state['clicked_button']['#id'] == 'edit-jnj-deploy-tool-upload-button') {
    if (!ereg('^' . variable_get('jnj_deploy_tool_packagename', 'backup.tgz') . '.*', $_FILES['files']['name']['jnj_deploy_tool_file_to_upload'])) {
      form_set_error('jnj_deploy_tool_file_to_upload', t('File name must start with \'') . variable_get('jnj_deploy_tool_packagename', 'backup.tgz') . t('\' according to settings (Deployment package main name).'));
    }
  }
}